package servlet;

import pojo.Users;
import service.UsersService;
import service.UsersServicesImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Date;

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    UsersService usersService = new UsersServicesImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        Users users = null;
        try {
            users = usersService.selectUsersByName(username);
//            System.out.println(users);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if (users.getLoginName().equals(username) && users.getPassword().equals(password)){
            HttpSession session = req.getSession();
            session.setAttribute("realName",users.getRealName());
            session.setAttribute("mytime",new Date());
            req.getSession().setAttribute("u1",users);
            resp.sendRedirect("index.jsp");
        }else {
            req.setAttribute("msg","用户名或者密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }
}
